package com.xspace.android.xafcommon.base;

import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.xspace.android.xafcommon.R;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.been.PageBean;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.PageUtil;
import com.xspace.android.xafcommon.view.ProgressLoading;
import com.xspace.android.xafcommon.view.dialog.DialogControl;

import java.util.Map;

import de.greenrobot.event.EventBus;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by liuchen on 2016/10/13.
 */

public abstract class BaseFragment extends Fragment {
    private static final String TAG = "BaseFragmen";
    private ProgressLoading mProgressLoading;
    private boolean progressShow;
    protected View mRoot;
    protected Context mContext;
    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;
    //    protected OkHttpClient okHttpClient;
    protected BaseReturnBean returnBean;
    protected boolean isCreate = false;
    protected Subscription subscription;
    protected int PAGE_INDEX = 0;
    protected static String PAGE_TURN = PageUtil.PAGE_DOWN;
    protected PageBean mPageBean = new PageBean();
    protected boolean isShowBack = false;
    protected boolean isShowTop = true;
    public static String IS_SHOW_BACK = "showback";
    public static String IS_SHOW_TOP = "showTop";
    private final CompositeSubscription mAllSubscription = new CompositeSubscription();
    /**
     * params to fragment
     */
    protected Bundle fragmentArgs;
    protected LayoutInflater mInflater;

    public BaseFragment() {
    }

    protected void registerSubscription(Subscription subscription) {
        mAllSubscription.add(subscription);
    }

    protected void unregisterSubscription(Subscription subscription) {
        mAllSubscription.remove(subscription);
    }

    protected void clearSubscription() {
        mAllSubscription.clear();
    }

    /**
     * 此方法可以得到上下文对象
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreate = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        clearSubscription();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    /*
         * 返回一个需要展示的View
         */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRoot != null) {
            LogUtil.d("onCreateView  复用");
            ViewGroup parent = (ViewGroup) mRoot.getParent();
            if (parent != null)
                parent.removeView(mRoot);
        } else {
            LogUtil.d("onCreateView  reload");
            mContext = getActivity();
            mInflater = LayoutInflater.from(mContext);
            inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
            fragmentArgs = getArguments();
            LogUtil.d("fragmentArgs" + (fragmentArgs == null));
            getIntentData();
            mRoot = initView(inflater);
            initFindViewById(mRoot);
            initEvent();
            initData();
        }
        return mRoot;
    }

    protected void getIntentData() {
        if (fragmentArgs != null) {
            isShowBack = fragmentArgs.getBoolean(IS_SHOW_BACK, false);
            isShowTop = fragmentArgs.getBoolean(IS_SHOW_TOP, true);
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    /**
     * 当Activity初始化之后可以在这里进行一些数据的初始化操作
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (isProgressShow() && mProgressLoading != null) {
            dismissProgressLoading();
            mProgressLoading = null;
        }
    }

    protected void hideSoftKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams
                .SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public boolean isProgressShow() {
        return progressShow;
    }

    public void dismissProgressLoading() {
        if (mProgressLoading != null && isVisible()) {
            progressShow = false;
            mProgressLoading.dismiss();
        }
    }

    /**
     * 子类可以复写此方法初始化事件
     */
    protected void initEvent() {

    }

    public ProgressLoading getProgressLoading() {
        return mProgressLoading;
    }

    public void showProgressLoading(String message) {
        if (mProgressLoading == null) {
            mProgressLoading = new ProgressLoading(mContext, R.style.ProgressLoadingTheme);
            mProgressLoading.setCanceledOnTouchOutside(true);
            mProgressLoading.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    progressShow = false;
                }
            });
        }
        if (!TextUtils.isEmpty(message)) {
            mProgressLoading.setMessage(message);
        } else {
            mProgressLoading.setMessage(null);
        }
        progressShow = true;
        mProgressLoading.show();
    }

    /**
     * 子类实现此抽象方法返回View进行展示
     *
     * @return
     */
    public abstract View initView(LayoutInflater inflater);

    /**
     * 初始化控件
     */
    protected abstract void initFindViewById(View view);

    /**
     * 子类在此方法中实现数据的初始化
     */
    public abstract void initData();

    public void onEventMainThread(Map<String, Object> inParam) {

    }

    protected void hideWaitDialog() {
        FragmentActivity activity = getActivity();
        if (activity instanceof DialogControl) {
            ((DialogControl) activity).hideWaitDialog();
        }
    }

    protected ProgressDialog showWaitDialog() {
        return showWaitDialog(R.string.loading);
    }

    protected ProgressDialog showWaitDialog(int resid) {
        FragmentActivity activity = getActivity();
        if (activity instanceof DialogControl) {
            ((DialogControl) activity).showWaitDialog(resid);
        }
        return null;
    }

    protected ProgressDialog showWaitDialog(String str) {
        FragmentActivity activity = getActivity();
        if (activity instanceof DialogControl) {
            ((DialogControl) activity).showWaitDialog(str);
        }
        return null;
    }

    protected void exitActivity() {
        getActivity().onBackPressed();
    }

    protected void exitActivity2() {
        getActivity().finish();
    }
}
